<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['basic:home:add']"
        >新增
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['basic:home:edit']"
        >修改
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['basic:home:remove']"
        >删除
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['basic:home:export']"
        >导出
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="homeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="小区名称" align="center" prop="communityId">
        <template #default="scope">
          {{getCommunityName(scope.row.communityId)}}
        </template>
      </el-table-column>
      <el-table-column label="房间位置" align="center" prop="homeLocation"/>
      <el-table-column label="业主" align="center" prop="ownerId">
        <template #default="scope">
          {{getOwnerName(scope.row.ownerId)}}
        </template>
      </el-table-column>
      <el-table-column label="面积" align="center" prop="area"/>
      <el-table-column label="使用面积" align="center" prop="usableArea"/>
      <el-table-column label="仓库面积" align="center" prop="warehouseArea"/>
      <el-table-column label="房间类型" align="center" prop="homeTypeIds">
        <template #default="scope">
            {{getTypeName(scope.row.homeTypeIds)}}
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="homeRemark"/>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:home:edit']"
          >修改
          </el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['basic:home:remove']"
          >删除
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房间资料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="门牌号" prop="communityName">
              <el-input v-model="form.homeNumber" placeholder="请输入房间门牌号" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积" prop="area">
              <el-input v-model="form.area" placeholder="请输入面积"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="使用面积" prop="usableArea">
              <el-input v-model="form.usableArea" placeholder="请输入使用面积"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库面积" prop="warehouseArea">
              <el-input v-model="form.warehouseArea" placeholder="请输入仓库面积"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="信息" >
              <el-cascader
                v-model="selectedOptions"
                :options="props"
                @change="handleChange"
                size="small"
                clearable
                style="width: 210px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="房间类型" prop="types">
              <el-checkbox-group v-model="form.homeTypeIds" size="small">
                <el-checkbox-button
                  v-for="city in typeList"
                  :label="city.homeTypeId"
                  :key="city.homeTypeId"
                >{{ city.homeType }}
                </el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业主" prop="ownerId">
              <el-select v-model="form.ownerId" placeholder="请选择业主">
                <el-option
                  v-for="item in ownerList"
                  :key="item.ownerId"
                  :label="item.ownerName"
                  :value="item.ownerId"
                  @keyup.enter.native="handleQuery"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.homeRemark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAllOwner,
  listHomeType,
  listHome,
  getHome,
  delHome,
  addHome,
  updateHome,
} from "@/api/basic/home";

import {cascade} from "@/api/basic/unitInfo";
import {listCommunity} from "@/api/basic/community";
import {listBalcony} from "@/api/basic/balcony";
import {listUnit} from "@/api/basic/unit";

export default {
  name: "Home",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房间资料表格数据
      homeList: [],
      communityList: [],
      balconyList: [],
      unitList: [],
      typeList: [],
      ownerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      props: {},
      selectedOptions:[],
      // 表单校验
      rules: {
        area: [
          {required: true, message: '请输入面积', trigger: 'blur'},
          {
            validator: this.validateAreaSum,
            trigger: 'blur'
          }
        ],
        usableArea: [
          {required: true, message: '请输入使用面积', trigger: 'blur'},
          {
            validator: this.validateAreaSum,
            trigger: 'blur'
          }
        ],
        warehouseArea: [
          {required: true, message: '请输入仓库面积', trigger: 'blur'},
          {
            validator: this.validateAreaSum,
            trigger: 'blur'
          }
        ],
        // 自定义验证规则
      },
    };
  },
  created() {
    this.getList();
    this.getTypeList();
    this.getOwners();
    this.getProps()
    this.getBalconyList()
    this.getUnitList()
    this.getCommunityList()
  },
  methods: {
    /** 查询小区列表 */
    getCommunityList() {
      listCommunity().then(response => {
        this.communityList = response.rows;
      });
    },
    /** 查询楼座列表 */
    getBalconyList() {
      listBalcony().then(response => {
        this.balconyList = response.rows;
      });
    },
    /** 查询单元列表*/
    getUnitList() {
      listUnit(this.queryParams).then(response => {
        this.unitList = response.rows;
      });
    },
    /** 查询所有业主 */
    getOwners() {
      listAllOwner(this.queryParams).then((response) => {
        this.ownerList = response.rows;
      });
    },
    getProps() {
      cascade().then(response => {
        this.props = response.data
        console.log(this.props)
      })
    },
    /** 查询房间类型 */
    getTypeList() {
      listHomeType(this.queryParams).then((response) => {
        this.typeList = response.rows;
      });
    },
    /** 查询房间资料列表 */
    getList() {
      this.loading = true;
      listHome(this.queryParams).then((response) => {
        this.homeList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.homeList)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        homeNumber: null,
        homeId: null,
        balconyid: null,
        unitid: null,
        communityId: null,
        homeLocation: null,
        homeLayserNumber: null,
        ownerId: null,
        area: null,
        usableArea: null,
        warehouseArea: null,
        homeRemark: null,
        del: null,
        homeTypeIds: [],
      };
      this.selectedOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加房间资料";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ids = row.id || this.ids;
      getHome(ids).then((response) => {
        this.form = response.data;
        this.selectedOptions = [this.form.communityId,this.form.balconyid,this.form.unitid]
        this.open = true;
        this.title = "修改房间资料";
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.homeId != null) {
            updateHome(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHome(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除房间资料编号为"' + ids + '"的数据项？')
        .then(function () {
          return delHome(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "basic/home/export",
        {
          ...this.queryParams,
        },
        `home_${new Date().getTime()}.xlsx`
      );
    },

    // 自定义验证函数
    validateAreaSum(rule, value, callback) {
      const {usableArea, warehouseArea, area} = this.form;
      // 判断输入值是否有效
      if (!usableArea || !warehouseArea || !area) {
        return callback();
      }

      // 将值转换为数字进行计算
      const usable = parseFloat(usableArea);
      const warehouse = parseFloat(warehouseArea);
      const totalArea = parseFloat(area);

      if (isNaN(usable) || isNaN(warehouse) || isNaN(totalArea)) {
        return callback(new Error('请输入有效的数字'));
      }

      // 判断 usableArea + warehouseArea 是否等于 area
      if (usable + warehouse !== totalArea) {
        return callback(new Error('使用面积 + 仓库面积 必须等于 面积'));
      }
      callback(); // 验证通过
    },
    handleChange(value) {
      console.log('Selected options:', value);
      console.log(this.selectedOptions)
      this.form.communityId = value[0]
      this.form.balconyid = value[1]
      this.form.unitid = value[2]
      console.log(this.form.communityId)
      console.log(this.form.balconyid)
      console.log(this.form.unitid)
    },
    getCommunityName(value){
      let communityName = ''
      this.communityList.forEach(community => {
        if (community.communityId === value) {
          communityName = community.communityName;
        }
      })
      return communityName
    },
    getOwnerName(value){
      let ownerName = '';
      this.ownerList.forEach(owner => {
        if (owner.ownerId === value) {
          ownerName = owner.ownerName;
        }
      })
      return ownerName
    },
    getTypeName(value){
      let typeName = [];
      this.typeList.forEach(type => {
        value.forEach(item => {
          if (type.homeTypeId ===item) {
            typeName.push(type.homeType)
          }
        })
      })
      return typeName.join('  ')
    }
  },
};
</script>
